// 只负责从后端获取并转换路由数据，不操作 router 实例
import type { RouteRecordRaw } from "vue-router";
import { getRouters } from "@/api/system/menu";

interface ApiRoute {
  name: string;
  path: string;
  hidden: boolean;
  redirect?: string;
  menuType: number;
  component: string;
  alwaysShow?: boolean;
  meta: {
    title: string;
    icon: string;
    noCache: boolean;
    link: string | null;
  };
  children?: ApiRoute[];
}

interface ApiResponse {
  code: number;
  msg: string;
  data: ApiRoute[];
}

const Layout = () => import("@/layouts/index.vue");

// 注意路径：从项目根目录开始匹配
const modules = import.meta.glob("/src/views/**/*.vue");

function loadView(viewPath: string) {
  // 清理路径：去除可能的前缀斜杠
  const cleanPath = viewPath.replace(/^\//, "");
  const targetPath = `/src/views/${cleanPath}.vue`;

  const component = modules[targetPath];
  if (component) {
    return () => component();
  }

  console.warn(`[路由] 未找到组件: ${viewPath} → ${targetPath}`);
  return () => import("@/views/error/404.vue");
}

export function filterAsyncRouter(
  routes: ApiRoute[],
  parentPath = ""
): RouteRecordRaw[] {
  return routes
    .filter((route) => route.menuType === 0 || route.menuType === 1)
    .map((route) => {
      // 构建完整路径
      const path = route.path.startsWith("/")
        ? route.path
        : `${parentPath}/${route.path}`.replace(/\/+/g, "/"); // 防止双斜杠

      const routeRecord: any = {
        name: route.name,
        path,
        hidden: route.hidden,
        meta: { ...route.meta },
        ...(route.redirect && route.redirect !== "noRedirect"
          ? { redirect: route.redirect }
          : {}),
        ...(route.alwaysShow !== undefined
          ? { alwaysShow: route.alwaysShow }
          : {}),
      };

      if (route.component === "Layout") {
        routeRecord.component = Layout;
      } else {
        routeRecord.component = loadView(route.component);
      }

      if (route.children && route.children.length > 0) {
        routeRecord.children = filterAsyncRouter(route.children, path);
      }

      return routeRecord as RouteRecordRaw;
    });
}

/**
 * ✅ 仅返回路由数组，不操作 router
 */
export async function loadDynamicRoutes(): Promise<RouteRecordRaw[]> {
  try {
    const res: ApiResponse = await getRouters({});
    if (res.code === 200 && Array.isArray(res.data)) {
      console.log("✅ 接口返回路由:", res.data);
      const routes = filterAsyncRouter(res.data);
      console.log("✅ 转换后的动态路由:", routes);
      return routes;
    } else {
      console.warn("❌ 路由接口返回异常:", res.msg);
      return [];
    }
  } catch (error) {
    console.error("❌ 加载动态路由失败:", error);
    return [];
  }
}
